package ru.onlinestore.mobile.data.sources.remote

import ru.onlinestore.mobile.core.Response
import ru.onlinestore.mobile.data.entities.ProductData
import ru.onlinestore.mobile.data.entities.ProductListData
import ru.onlinestore.mobile.data.sources.ProductsRemoteSource
import ru.onlinestore.mobile.data.sources.remote.dto.ProductListDTO

class ProductsRemoteSourceImpl(
    private val service: ProductsApiService
): ProductsRemoteSource {

    override suspend fun fetchProductList(): Response<ProductListData> {
        return try {
            val productList = service.fetchProductList().await()

            if (productList.products.isNotEmpty()) {
                Response.Success(
                    data = productList.map { list ->
                        ProductListData(
                            products = list.products.map { product ->
                                ProductData(
                                    id = product.id,
                                    title = product.title,
                                    description = product.description,
                                    price = product.price,
                                    brand = product.brand ?: "",
                                    category = product.category,
                                    thumbnail = product.thumbnail,
                                    images = product.images
                                )
                            },
                            total = list.total,
                            skip = list.skip,
                            limit = list.limit
                        )
                    }
                )
            } else {
                Response.Empty()
            }
        } catch (exception: Exception) {
            Response.Error(
                exception = exception
            )
        }
    }
}